<?php

namespace App\Services;

use App\Common\Libs\ArrayHelper;
use App\Common\Libs\IdBuilder;
use App\Exceptions\Error;
use App\Formats\NoteFormat;
use App\Models\Cache\Cache;
use App\Models\Cache\CacheKey;
use App\Models\Field\TopicField;
use App\Models\IndexNote;
use App\Models\Select\TopicSelect;
use App\Models\SysTopic;

class TopicService extends BaseService
{
    public $_repository;
    private $_topic;

    public function __construct()
    {
        parent::__construct();
        $this->_repository = repository()->TopicRepository;
    }

    public function getSearchTopicList($searchParams)
    {
        $dataProvider = $this->_repository->getTopicList($searchParams);
        $pagination = $this->getPagination();
        $indexTopics = $dataProvider->getModels();

        $list = $this->formatTopics($indexTopics);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    public function getTopicList($searchParams)
    {
        $dataProvider = $this->_repository->getTopicList($searchParams);
        $pagination = $this->getPagination();
        $indexTopics = $dataProvider->getModels();

        $list = $this->formatTopics($indexTopics);

        return self::outputMoreList($dataProvider, $pagination, $list);
    }

    /**
     * 格式化话题
     * @param $topics
     * @return array
     */
    private function formatTopics($topics)
    {
        // 根据topic_id得到分表
        $topicIdTable = IdBuilder::getSubTable(ArrayHelper::getColumn($topics, 'topic_id'));

        // 话题
        $topicArr = [];
        foreach ($topicIdTable as $tableCount => $topicIdArr) {
            $models = $this->_repository->getTopicByTableCount($tableCount, $topicIdArr, TopicSelect::SELF_LIST);
            $topicArr = ArrayHelper::merge($topicArr, $models);
        }

        $list = [];
        /**
         * @var SysTopic $topic
         */
        foreach ($topicArr as $topic) {
            $count = service()->CounterService->getTargetCount(CacheKey::COUNTER_TOPIC, [
                'hot',
            ], ['topic_id' => $topic->topic_id]);
            $list[] = ArrayHelper::merge($topic->commonFormat(TopicField::SELF_LIST), [
                'count' => $count,
                'hot' => $count['hot']
            ]);
        }

        $list = ArrayHelper::multisort($list, 'hot', SORT_DESC);

        return $list;
    }

    public function getTopicTargets($searchParams)
    {
        $ignoreTargetId = Cache::getInstance([
            'topic_id' => $searchParams['topic_id']
        ])->get(CacheKey::TOPIC_DETAIL_TARGET_ID);
        if ($ignoreTargetId) {
            $searchParams['ignore_target'] = explode(',', $ignoreTargetId);
        }

        $dataProvider = $this->_repository->getTopicTargetsList($searchParams);
        $pagination = $this->getPagination();
        $targets = $dataProvider->getModels();
        $noteList = $this->formatTopicTargets($targets, $searchParams['current_user_id']);

        $noteList = ArrayHelper::multiSort($noteList, 'created_at', SORT_DESC);

        return self::outputMoreList($dataProvider, $pagination, $noteList);
    }

    public function getTopic($topicId, $selectScene = TopicSelect::SELF_DETAIL)
    {
        if (empty($this->_topic[$topicId])) {
            $topic = $this->_repository->getTopicById($topicId, $selectScene);
            if (!$topic) {
                return false;
            }
            $this->_topic[$topicId] = $topic;
        }
        return $this->_topic[$topicId];
    }

    /**
     * 获取话题其他信息
     * @param SysTopic $topic
     * @return array|bool
     */
    public function getTopicMoreInfo($topic, $currentUserId)
    {
        $topTargets = $this->_repository->getTopicTopTargets($topic->topic_id);
        $hotTargets = $this->_repository->getTopicHotTargets($topic->topic_id, ArrayHelper::getColumn($topTargets, 'target_id'));

        $allTargets = ArrayHelper::merge($topTargets, $hotTargets);
        $noteList = $this->formatTopicTargets($allTargets, $currentUserId);

        $noteList = ArrayHelper::index($noteList, 'id');

        $topList = [];
        $topTargetsIdArr = ArrayHelper::getColumn($topTargets, 'target_id');
        $hotList = [];
        $hotTargetsIdArr = ArrayHelper::getColumn($hotTargets, 'target_id');

        foreach ($noteList as $note) {
            if (in_array($note['id'], $topTargetsIdArr)) {
                $topList[] = $note;
            } elseif (in_array($note['id'], $hotTargetsIdArr)) {
                $hotList[] = $note;
            }
        }

        // 将【热门】【置顶】【关注】的话题内容ID，以逗号分隔存入缓存
        $this->topicTargetIdToCache($topic->topic_id, ArrayHelper::merge($topTargetsIdArr, $hotTargetsIdArr));

        return [
            'top' => $topList,
            'hot' => $hotList,
        ];
    }

    public function topicTargetIdToCache($topicId, $targetIdArr)
    {
        Cache::getInstance([
            'topic_id' => $topicId
        ])->set(CacheKey::TOPIC_DETAIL_TARGET_ID, implode(',', (array)$targetIdArr));
    }

    private function formatTopicTargets($targets, $currentUserId)
    {
        $indexNoteArr = IndexNote::getInstance()->whereIn('note_id', ArrayHelper::getColumn($targets, 'target_id'))->get();
        return formats()->NoteFormat->formatNoteList(ArrayHelper::getColumn($indexNoteArr, 'note_id'), $currentUserId, NoteFormat::TOPIC_LIST);
    }
}
